<template>
  <div class="charts-index" v-loading.fullscreen.lock="isLoading">
    <div class="charts-left">
      <div class="charts-left-fixed">
        <div class="charts-index-back">
          <i class="iconfont icon-return"></i>
          <span class="charts-index-back-text" @click="handleBack">返回</span>
          <!-- <span class="charts-index-back-title">智能报表</span> -->
        </div>
        <div class="charts-index-search">
          <el-input v-model="menuKeyword" placeholder="关键字搜索" @input="searchKeyword($event)">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
        <charts-menu
          :is-open-all="isOpenAllMenus"
          :menu-data="menuData"
          @chartsValue="getChartsValue"
          :charts-value="chart"
          :chart-parent="chartParent"/>
      </div>
    </div>

    <div class="charts-right">
      <charts-header 
        class="charts-header"
        :charts-value="pageInfo"
        :chart-option="currentChartOptions"
        @switch="switchSampleData"
      />
      <charts-search 
        class="charts-search"
        :report-key="reportKey"
        :value="currentChartSearchParams" 
        @input="handlerChartSearchChange" 
        @reset="handlerChartSearchReset" 
        @search="handlerChartSearch" 
      />
      <div>
        <div class="charts-content">
          <!-- 筛选组件 -->
          <div
            v-if="optionType"
            class="chart-card" 
            :class="{
              'chart-card-header': cardStyle,
              'card-radius': !noStockTurnover
            }" 
          >
          <component
            :is="optionType"
            :ref="optionType"
            :page-info="pageInfo"
            :chart-type="chart"
            :is-example="isExample"
            :chart-option="currentChartOptions"
            @fetchChartData="fetchChartData"
          ></component>
          </div>
          <!-- 图表组件 -->
          <div 
            class="charts-content-two" 
            :class="{
              'chart-card-box': cardStyle,
              'chart-card-radius': noStockTurnover
            }"
          >
          <component
            :is="`${chartType}-chart`"
            :chart-type="reportKey"
            :chart-data="chartData"
            :line-chart-data="lineChartData"
            :pie-chart-data="pieChartData"
            :pie-table-data="pieTableData"
            :income-pay-data="incomePayData"
            :ranking-map="rankingMap"
            :line-table-data="lineTableData"
            :table-page-params="tablePageParams"
            :chart-option="currentChartOptions"
            :fetch-params="fetchParams"
            :show-pie-table="showPieTable"
            :show-line-table="showLineTable"
            :show-task-table="showTaskTable"
            :spare-parts-data="sparePartsData"
            :sales-map="salesMap"
            :user-module-auth="userModuleAuth"
            @foldTable="foldTable"
            @foldTaskTable="foldTaskTable"
            @fetchChartData="fetchChartData"
            @fetchTableData="fetchTableData"
            @handleSizeChange="handleSizeChange"
            @handleNumChange="handleNumChange"
            @categoryMore="categoryMore"
            @export="exportTableData"
          ></component>
          </div>
          <!-- 下钻图表 -->
          <div class="chart-card-box" v-show="notTaskSatisfaction && isTableShow">
          <DrillDownTable
            v-if="notTaskSatisfaction"
            v-show="isTableShow"
            :positionTime="positionTime"
            :chart-type="chart"
            :table-data="tableData"
            :table-page-params="tablePageParams"
            :time-unit="timeUnit"
            :chart-option="currentChartOptions"
            :table-period-select-tabs="tablePeriodSelectTabs"
            :user-module-auth="userModuleAuth"
            @fetchTableData="fetchTableData"
            @changePeriodTableSelectTabs="changePeriodTableSelectTabs"
            @foldTable="foldTable"
            @export="exportTableData"
            @getCellData="getCellData"
            @handleSizeChange="handleSizeChange"
            @handleNumChange="handleNumChange"
          />
          <!-- 二期更换工单组件后 删掉这个table -->
          <chart-task-table
            v-if="isRepeatedMaintenanceRate"
            ref="chartTaskTable"
            v-show="showTaskTable"
            :chart-type="chart"
            :chart-option="currentChartOptions"
            :fetch-params="fetchParams"
            :user-module-auth="userModuleAuth"
            @export="exportTableData"
            @getCellData="getCellData"
          />
          <!-- 二期更换工单组件后 删掉这个table -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* components */
import {
  ChartsMenu,
  ChartsHeader,
  ChartTimeOptionSetting,
  ChartComment,
  ChartPeriodSetting,
  ChartInspectionTimeSetting,
  ChartTaskOptionSetting,
  ChartStockTurnoverOptionSetting,
  ChartSatisfiedPeriodSetting,
  ChartRepeatMaintenanceSetting,
  ChartTaskTable
} from './components/common/index';
import ChartsSearch from '@src/modules/report/managementReport/charts/components/common/ChartsSearch/ChartsSearch.tsx'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum.ts'

import {
  StackedLineChart,
  BarChart,
  BarLineChart,
  PieChart,
  PieStackedLineChart,
  IncomePayChart,
  DrillDownTable,
  BarRevenueChart,
} from './components/index.ts';
import qs from '@src/util/querystring';
import { managementReportChartList } from '../ManagementReportModel';
import http from 'src/util/HttpUtil';
/* model */
import { 
  ChartsSearchParams,  
  ChartsSearchFetchParams, 
  ChartsTeamRankingDataParams,
  ChartsSparePartsDataParams,
} from '@src/modules/report/managementReport/charts/components/common/ChartsSearch/ChartsSearchModel'
/* api */
import { 
  getReportThemeTree,
  getCloseAroundData,
  getSatisfactionPine,
  getProfitData,
  getIncomeRanking,
  getProfitRanking,
  getSalesStructureData,
  getServiceIncomeProfitData,
  getSpareIncomeProfitData,
  getRepeatBroken,
  exportResponsePartData,
  exportServicePartData,
  exportMaintenancePartData,
  exportClosingPartData,
  exportHumanPartData,
  exportRepeatedPartData,
  exportRepeatedTaskPartData,
  exportTaskReturnPartData,
  exportTaskSatisfactionPiePartData,
  exportTaskSatisfactionBrokenLinePartData,
  exportTaskSatisfactionPieTaskPartData,
  getRepeatBrokenTaskData,
  getUserModuleAuth,
} from '@src/api/ManagementReport'
/* util */
import { parse } from '@src/util/date'
import DateUtil from '@src/util/date'
import { safeNewDate } from '@src/util/time';

export default {
  data() {
    return {
      // 当前报表搜索参数
      currentChartSearchParams: undefined,
      // 报表搜索参数对象 格式为 { [reportKey]: { 搜索参数 } }
      reportKeySearchParamsMap: {},
      menuKeyword: '',
      reportKey: '',
      parentKey: '',
      pageInfo: {},
      // 过滤后的当前图表搜索入参
      fetchParams: undefined,
      // 过滤后当前图表搜索入参对象 格式为 { [reportKey]: {搜索参数} }
      fetchParamsMap: {},
      // 分页参数
      tablePageParams: {
        page: 1,
        pageSize: 10,
        totalSize: 0
      },
      chartData: [],
      lineChartData: [],
      pieChartData: {},
      incomePayData: {},
      // 下钻数据
      tableData: [],
      // 满意度饼图下钻数据
      pieTableData: [],
      // 满意度折线下钻数据
      lineTableData: [],
      showPieTable: false,
      showLineTable: false,
      showTaskTable: false,
      // 维度组件参数集合
      chartOption: {},
      // 当前维度组件参数
      currentChartOptions: null,
      menuData: [],
      // 显示下钻列表
      isTableShow: false,
      // 平均服务用时单位
      timeUnit: undefined,
      isLoading: false,
      // 收支结构分析 团队排行
      rankingMap: new ChartsTeamRankingDataParams(),
      categoryType: '',
      // 备件营收
      sparePartsData: {},
      // 备件明细 服务项目明细
      salesMap: new ChartsSparePartsDataParams(),
      isExample: false,
      tablePeriodSelectTabs: '0',
      aroundSearchQueryList: [],
      repeatedSearchQueries: [],
      userModuleAuth: {}, // 是否有模块权限
      positionTime: ''
    };
  },
  computed: {
    queryObject() {
      return qs.parse(window.location.search) || {};
    },
    // 二级菜单
    chart() {
      return this.reportKey
    },
    // 一级菜单展开传值
    chartParent() {
      return this.parentKey
    },
    chartType() {
      return this.pageInfo?.type || 'bar';
    },
    optionType() {
      return this.pageInfo?.optionCom || null;
    },
    notTaskSatisfaction() {
      return this.reportKey !== 'task-customer-satisfaction'
    },
    isRepeatedMaintenanceRate() {
      return this.reportKey === 'repeated-maintenance-rate'
    },
    cardStyle(){
      return  ['bar','bar-line','stacked-line'].some(x => this.chartType === x);
    },
    noStockTurnover(){
      return this.cardStyle && this.optionType !== 'chart-stock-turnover-option-setting';
    },
    isOpenAllMenus() {
      return Boolean(this.menuKeyword)
    }
  },
  watch: {
    // reportKey 改为chart
    chart(newReportKey) {
      if (!this.reportKeySearchParamsMap[newReportKey]) {
        this.reportKeySearchParamsMap[newReportKey] = new ChartsSearchParams();
        this.fetchParamsMap[newReportKey] = new ChartsSearchFetchParams(newReportKey)
      }
      
      this.fetchParams = this.fetchParamsMap[newReportKey]
      this.currentChartOptions = this.chartOption[newReportKey]

      this.$nextTick(()=>{
        this.buildPeriodTime(newReportKey)
      })
    }
  },
  methods: {
    buildPeriodTime(newReportKey) {
      try {
        if (this.fetchParams.dimension === 1) {
          this.reportKeySearchParamsMap[newReportKey].type = 'week';
        } 
        else if (this.fetchParams.dimension === 2) {
          this.reportKeySearchParamsMap[newReportKey].type = 'month';
        } 
        else if (this.fetchParams.dimension === 3) {
          this.reportKeySearchParamsMap[newReportKey].type = 'quarter';
        } 
        else if (this.currentChartSearchParams.type === 4) {
          this.reportKeySearchParamsMap[newReportKey].type = 'year';
        }
        
        if (this.fetchParams.startTime) {
          this.reportKeySearchParamsMap[newReportKey].timeStart = this.fetchParams.startTime
          if (!this.reportKeySearchParamsMap[newReportKey]?.periodStartDate) {
            this.reportKeySearchParamsMap[newReportKey].periodStartDate = parse(this.fetchParams.startTime)
          }
        }
        
        if (this.fetchParams.endTime) {
          this.reportKeySearchParamsMap[newReportKey].timeEnd = this.fetchParams.endTime
          if (!this.reportKeySearchParamsMap[newReportKey]?.periodEndDate) {
            this.reportKeySearchParamsMap[newReportKey].periodEndDate = parse(this.fetchParams.endTime)
          }
        }

        this.currentChartSearchHidePeriod(newReportKey);
        // TODO: 初始纬度为月，但是开始时间是当前时间的一个月之前，如何显示。
        
        this.currentChartSearchParams = this.reportKeySearchParamsMap[newReportKey]
      } catch (error) {
        console.log(error)
      }
    },
    getChartsValue(chartsValue) {
      this.reportKey = chartsValue.routingKey
      this.parentKey = chartsValue.parentKey

      // 重置table分页
      this.tablePageParams = {
        page: 1,
        pageSize: 10,
        totalSize: 0
      }
      this.$nextTick(() => {
        if(this.reportKey === 'spare-parts-satisfy'){
          this.reportKeySearchParamsMap[this.reportKey].sparepartIdList = [];
        }
        if (this.optionType && this.$refs[this.optionType].refresh) {
          this.$refs[this.optionType].refresh();
        }

        this.getCurrentPageData();
      })
    },
    /** 
     * @description 获取菜单数据
     * @param String keyword 菜单搜索参数
    */
    getMenuData(e = '') {
      getReportThemeTree(e).then(res => {
        if (res.code === 200) {
          let data = res.data || {}
          let dataList = data.reportThemeList || []

          let reportThemeList = dataList.filter(item => item.reportThemeList)
          reportThemeList = this.handlerFilterReportThemeList(reportThemeList, ['UNFINISHEDWO'])
          this.selectMenuActive(e, reportThemeList)
          this.menuData = reportThemeList
          // this.getCurrentPageInfo()
        } else {
          this.$message({
            message: res.msg,
            duration: 1500,
            type: 'error',
          });
        }
      }).catch(err => {
        console.log(err);
      })
    },
    handlerFilterReportThemeList(reportThemeList, filterKeys) {
      return reportThemeList.filter(item => {
        if (item?.reportThemeList) {
          item.reportThemeList = this.handlerFilterReportThemeList(item.reportThemeList, filterKeys)
        }
        
        return !filterKeys.includes(item.reportKey)
      })
    },
    selectMenuActive(e, data) {
      if(!data.length) return
      // 搜索时默认展开和选中第一个
      let chartName = e ? 
      data[0].reportThemeList[0].routingKey : 
      this.queryObject?.chartName

      let menuName = e ? 
      data[0].reportKey : 
      this.queryObject?.menuName

      // this.reportKey = chartName
      this.parentKey = menuName
    },
    searchKeyword(e) {
      this.getMenuData(e)
    },
    handleBack() {
      window.history.back();
    },
    /** 
     * @description 图表搜索变化事件
     * @param {Object } searchParams 图表搜索参数
    */
    handlerChartSearchChange(searchParams = {}) {
      const oldType = this.reportKeySearchParamsMap[this.reportKey]?.type;
      const newType = searchParams?.type;
      
      if (!this.reportKey) return

      // 切换周期情况开始结束时间
      if(oldType !== newType){
        searchParams.periodStartDate = '';
        searchParams.periodEndDate = '';
        searchParams.timeStart = '';
        searchParams.timeEnd = '';
      }
      if((searchParams.type === 'month' || searchParams.type === 'week') && searchParams.periodEndDate && oldType !== newType){
        const ol = safeNewDate(this.reportKeySearchParamsMap[this.reportKey].timeStart) || '';
        const nl = safeNewDate(searchParams.timeStart) || '';
        if(ol?.getTime() !== nl?.getTime()) {
          searchParams.timeEnd = DateUtil.format(searchParams?.periodEndDate, 'yyyy-MM-dd') || '';
        }
      }

      // 切换仓库 清空之前选中的备件
      if(searchParams.repertoryIdList !== this.reportKeySearchParamsMap[this.reportKey].repertoryIdList){
        searchParams.sparepartIdList = [];
      }

      this.reportKeySearchParamsMap[this.reportKey] = searchParams

      this.currentChartSearchHidePeriod(this.reportKey);
      this.currentChartSearchParams = this.reportKeySearchParamsMap[this.reportKey];
      
      // console.log('handlerChartSearchChange ~ this.currentChartSearchParams', this.currentChartSearchParams)
    },
    /** 
     * @description 图表搜索重置事件
    */
    handlerChartSearchReset() {
      this.reportKeySearchParamsMap[this.reportKey] = new ChartsSearchParams()
      this.fetchParamsMap[this.reportKey] = new ChartsSearchFetchParams(this.reportKey)
      // this.currentChartSearchHidePeriod(this.reportKey);

      this.fetchParams = this.fetchParamsMap[this.reportKey]
      this.currentChartSearchParams = this.reportKeySearchParamsMap[this.reportKey]

       this.buildPeriodTime(this.reportKey)
    },
    /** 
     * @description 图表搜索事件
    */
    handlerChartSearch() {
      // this.isLoading = true
      this.changeFetchParams();
      this.fetchChartData(this.currentChartOptions);
    },
    changeFetchParams() {
      // 每个指标下对应的搜索参数
      const tags = this.currentChartSearchParams.tags.map(item => item.id);

      let dimension = 0;
      // 统计维度: 0:天 1:周 2:月 3:季度 4:年
      if (this.currentChartSearchParams.type === 'week') {
        dimension = 1;
      } else if (this.currentChartSearchParams.type === 'month') {
        dimension = 2;
      } else if (this.currentChartSearchParams.type === 'quarter') {
        dimension = 3;
      } else if (this.currentChartSearchParams.type === 'year') {
        dimension = 4;
      }

      let filterParams = {
        tags,
        taskTypes: this.currentChartSearchParams.taskTypeIds,
        startTime: this.currentChartSearchParams.timeStart,
        endTime: this.currentChartSearchParams.timeEnd,
        dimension,
        userIdList: this.currentChartSearchParams.userIds,
        repertoryIdList: this.currentChartSearchParams.repertoryIdList ? [this.currentChartSearchParams.repertoryIdList] : [],
        sparepartIdList: this.currentChartSearchParams.sparepartIdList,
        serviceTypeList: this.currentChartSearchParams.serviceTypeList
      }
      this.fetchParamsMap[this.reportKey] = filterParams
      this.fetchParams = filterParams
    },
    // 搜索中需要隐藏的时间周期
    currentChartSearchHidePeriod(key){
      // 天
      const hideDayItem = ['task-return-visit', 'task-customer-satisfaction', 'timely-closing-rate'];
      // 天、周
      const hideWeekAndDayItem = ['spare-parts-turnover', 'spare-parts-satisfy', 'revenue-expenditure-analysis', 'spare-part-sale', 'repeated-maintenance-rate'];
      // 只展示月
      const showMonthItem = ['service-human-efficiency'];

      if(hideDayItem.some(x=> x===this.chart)){
        this.reportKeySearchParamsMap[key].hidePeriodList = ['isHideDate'];
      }else if(hideWeekAndDayItem.some(x=> x===this.chart)) {
        this.reportKeySearchParamsMap[key].hidePeriodList = ['isHideDate', 'isHideWeek'];
      }else if(showMonthItem.some(x=> x===this.chart)) {
        this.reportKeySearchParamsMap[key].hidePeriodList = ['isHideDate', 'isHideWeek', 'isHideQuarter', 'isHideYear'];
      }
    },
    // 获取当前页面图表信息（标题、描述、类型等……）
    getCurrentChartInfo() {
      const menuObj = managementReportChartList.find(item => item.value === this.chartParent) || {};
      if (!menuObj.children) return;

      this.pageInfo = menuObj.children.find(item => item.value === this.chart);
    },
    getCurrentPageData() {
      this.getCurrentChartInfo();

      this.fetchChartData(this.currentChartOptions);
    },
    // 获取当前图表的数据
    async getCurrentChartData(params) {
      this.chartData = []
      // this.foldTable()

      try {
        if (!this.pageInfo?.chartUrl) {
          this.isLoading = false
          return
        }
        
        const { code, msg, data } = await http.post(this.pageInfo.chartUrl, params);
        if (code !== 200) {
          this.chartData = []
          return this.$message({
            message: msg || '请求异常',
            duration: 1500,
            type: 'error',
          });
        }
        // 及时关单率dataDeliveryFormDTOS 服务人效dataProductivityDTOS 工单回访率dataReviewFormDTOS 工单满意度折线dataSatisfactionBrokenDTOList 备件满足率resultList
        this.chartData = data?.dataTurnAroundFormVOS || 
        data?.dataProductivityDTOS || 
        data?.dataDeliveryFormDTOS || 
        data?.dataReviewFormDTOS || 
        data?.dataSatisfactionBrokenDTOList || 
        data?.resultList || []
        // 工单回访率
        if (this.chart === 'task-return-visit') {
          // 处理企微人员
          if (this.isOpenData) {
            if (window.WWOpenData?.initCanvas) {
              window.WWOpenData.initCanvas()
              window.WWOpenData.enableCanvasSharing()
            }

            let allHandleStaffDataPromise = this.handleStaffData(this.chartData)
            await Promise.all([allHandleStaffDataPromise])
          }
        }
        // 工单满意度
        if (this.chart === 'task-customer-satisfaction') {
          // 处理企微人员
          if (this.isOpenData) {
            if (window.WWOpenData?.initCanvas) {
              window.WWOpenData.initCanvas()
              window.WWOpenData.enableCanvasSharing()
            }

            let allHandleStaffDataPromise = this.handleStaffData(this.chartData)
            await Promise.all([allHandleStaffDataPromise])
          }
        }
        // 库存周转率 
        if (this.chart === 'spare-parts-turnover') {
          this.chartData = data || []
        }
        // 收支结构分析
        if (this.chart === 'revenue-expenditure-analysis') {
          this.incomePayData = data || {}
        }
        // 收支结构分析
        if (this.chart === 'spare-part-sale') {
          // 处理企微人员
          if (this.isOpenData) {
            if (window.WWOpenData?.initCanvas) {
              window.WWOpenData.initCanvas()
              window.WWOpenData.enableCanvasSharing()
            }

            let allHandleStaffDataPromise = this.handleStaffData(data?.countList?.list)
            await Promise.all([allHandleStaffDataPromise])
          }
          this.sparePartsData = data || {}
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.isLoading = false
      }
    },
    async getData(getDataFunction, params) {
      let result = {}
      try {
        const { code, data, msg } = await getDataFunction(params)
        if (code !== 200) {
          this.isLoading = false
          return this.$message({
            message: msg,
            duration: 1500,
            type: 'error',
          })
        }
        result = data || {}
        this.isLoading = false
      } catch (error) {
        console.log(error)
      }
      return result
    },
    fetchChartData(value, chartType) {
      this.isLoading = true
      this.foldTable(false)
      // 根据不同组件获取不同的请求参数
      if (this.optionType === 'chart-time-option-setting') {
        // 平均响应用时、平均服务用时、平均维修用时
        this.fetchTimeOptionChartData(value);

      } else if (this.optionType === 'chart-comment') {
        // 服务人效
        this.chartOption[this.reportKey] = { selectTimeUnit: 3 };
        this.currentChartOptions = this.chartOption[this.reportKey]
        this.getCurrentChartData(this.fetchParams);

      } else if (this.optionType === 'chart-period-setting' || this.optionType === 'chart-inspection-time-setting') {
        // 及时关单率、重复维修率
        this.fetchPeriodOptionChartData(value);
      } else if (this.optionType === 'chart-repeat-maintenance-setting') {
        // 重复维修率
        this.fetchRepeatMaintenanceOptionChartData(value)
      } else if (this.optionType === 'chart-task-option-setting') {
        // 工单回访率
        this.fetchTaskOptionChartData(value)
      } else if (this.optionType === 'chart-stock-turnover-option-setting') {
        // 库存周转率
        this.fetchStockTurnoverOptionChartData(value)
      } else if (this.optionType === 'chart-satisfied-period-setting') {
        // 备件满足率
        if (!this.chartOption[this.reportKey]?.satisfyCycle) {
          this.chartOption[this.reportKey] = { satisfyCycle: 48 }
        }

        if (value) {
          this.chartOption[this.reportKey] = value
        }
        this.currentChartOptions = this.chartOption[this.reportKey]
        const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)
        this.getCurrentChartData(params)
      }else {
        // 收支结构分析
        if (this.chart === 'revenue-expenditure-analysis') {
          return this.fetchIncomePayOptionChartData(value, chartType)
        } else if(this.chart === 'spare-part-sale'){
          // 备件营收分析
          return this.fetchChartMeetReatOptionChartData(value, chartType)
        }
        // 工单客户满意度
        this.fetchTaskOptionChartData(value)
      }
    },
    // 重复维修率
    async fetchRepeatMaintenanceOptionChartData(value) {
      this.$nextTick(async() => {
        if (value) {
          this.chartOption[this.reportKey] = value
        } else {
          // this.chartOption[this.reportKey] = this.$refs[this.optionType].closeForm;
          this.chartOption[this.reportKey] = {
            repeatedSearchQueries: [
              {
                searchIndex: 30
              },
              {
                searchIndex: 90
              }
            ]
          }
        }
        this.currentChartOptions = this.chartOption[this.reportKey]
        const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)

        this.getCurrentChartData(params)

        this.lineChartData = []
        const data = await this.getData(getRepeatBroken, params)
        this.lineChartData = data?.closeAroundList
      })
    },
    // 备件营收分析
    async fetchChartMeetReatOptionChartData(value = {}, chartType){
      let option = {};
      // 查询方式
      if (!this.chartOption[this.reportKey]?.selectType) {
        option.selectType = '0';
        option.page = 1;
        option.pageSize = 10;
      }
      // 选择地址的方式
      if (!this.chartOption[this.reportKey]?.addressType) {
        option.addressType = '1';
      }
      // 地址集合
      if (!this.chartOption[this.reportKey]?.areaCodeList) {
        option.areaCodeList = [];
      }
      // 部门
      if (!this.chartOption[this.reportKey]?.tags) {
        option.tags = [];
      }
      // 人员
      if (!this.chartOption[this.reportKey]?.users) {
        option.users = [];
      }

      this.chartOption[this.reportKey] = option;
      if (value) {
        this.chartOption[this.reportKey] = {
          ...this.chartOption[this.reportKey],
          ...value
        }
      }

      // 重置收入 利润图表
      if (!(['meetSelectType', 'spareIncomeProfitData', 'serviceIncomeProfitData', 'incomeProfit'].findIndex(item => item === chartType) > -1)) {
        this.salesMap = new ChartsSparePartsDataParams();
        this.chartOption[this.reportKey].page = 1;
      }

      this.currentChartOptions = this.chartOption[this.reportKey];

      // 去除不传递的数据
      const {
          pageSize, 
          selectType, 
          addressType,
          areaCodeList,
          tags,
          users,
          isExample,
      } = this.chartOption[this.reportKey];

      const newChartOption = {
        page: 1,
        pageSize,
        selectType,
        addressType,
        isExample,
      }

      if(selectType == '0'){
          newChartOption.areaCodeList = areaCodeList;
          this.chartOption[this.reportKey].tags = [];
          this.chartOption[this.reportKey].users = [];
      }else if(selectType == '3'){
          newChartOption.tags = tags;
          this.chartOption[this.reportKey].areaCodeList = [];
          this.chartOption[this.reportKey].users = [];
      }else if(selectType == '4'){
          newChartOption.users = users || [];
          this.chartOption[this.reportKey].areaCodeList = [];
          this.chartOption[this.reportKey].tags = [];
      }

      const params = Object.assign({}, this.fetchParams, newChartOption);
      if(selectType != '3'){
        params.tags = [];
      }
      if(params.tags?.length){
        params.tags = params.tags.map(x=>x.id);
      }
      if(params.areaCodeList?.length){
        params.areaCodeList = params.areaCodeList.map(x => x[x.length-1]);
      }

      this.featchMeetRateOptionChartData(params, chartType);
    },
    // 备件营收分析 接口请求
    async featchMeetRateOptionChartData(params, chartType){
      if(chartType === 'meetSelectType'){
        await this.getCurrentChartData(params);
      }else if(chartType === 'spareIncomeProfitData') {
        await this.getMeetRateData(params, chartType, getSpareIncomeProfitData);
      }else if(chartType === 'serviceIncomeProfitData') {
        await this.getMeetRateData(params, chartType, getServiceIncomeProfitData);
      }else if(chartType === 'incomeProfit') {
        await this.getMeetRateData(params, 'spareIncomeProfitData', getSpareIncomeProfitData);
        await this.getMeetRateData(params, 'serviceIncomeProfitData', getServiceIncomeProfitData);
      }else {
        this.$nextTick(()=>{
          this.sparePartsData = {};
        })
        await this.getCurrentChartData(params);
        await this.getMeetRateData(params, 'spareIncomeProfitData', getSpareIncomeProfitData);
        await this.getMeetRateData(params, 'serviceIncomeProfitData', getServiceIncomeProfitData);
      }
    },
    // 备件营收分析 收入和利润明细数据获取
    async getMeetRateData(params, chartType, getDataFunction) {
      const { dimension, startTime, endTime, serviceTypeList, tags, taskTypes, detailRadio } = params;
      const { page } = this.salesMap[chartType];
      const data = await this.getData(getDataFunction, {
        dimension,
        startTime,
        endTime,
        page: page || 1,
        pageSize: 10,
        serviceTypeList,
        tags,
        taskTypes,
        selectType: detailRadio || '0',
        isExample: this.isExample
      });

      this.salesMap[chartType].data = this.salesMap[chartType].data.concat(data.list || [])
      this.salesMap[chartType].hasNextPage = data.hasNextPage;
    },
    // 收支结构分析参数处理
    async fetchIncomePayOptionChartData(value, chartType) {
      let options = {}
      // 统计来源
      if (!this.chartOption[this.reportKey]?.dataSource) {
        options.dataSource = '1'
      }
      // 团队排行筛选
      if (!this.chartOption[this.reportKey]?.selectName) {
        options.selectName = '' // 等后端改成空字符串
      }
      // 利润筛选
      if (!this.chartOption[this.reportKey]?.selectType) {
        options.selectType = ''
      }

      if (!this.chartOption[this.reportKey]?.tagId) {
        options.tagId = ''
        options.page = 1
        options.pageSize = 10
      }

      this.chartOption[this.reportKey] = options

      if (value) {
        this.chartOption[this.reportKey] = {
          ...value,
          // ...this.chartOption[this.reportKey],
          
        }
      }
      if (!(['teamIncome', 'teamProfit', 'staffIncome', 'staffProfit', 'ratioChart'].findIndex(item => item === chartType) > -1)) {
        this.rankingMap = new ChartsTeamRankingDataParams()
        this.chartOption[this.reportKey].tagId = ''
        this.chartOption[this.reportKey].page = 1
      }
      this.currentChartOptions = this.chartOption[this.reportKey]
      const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)
      params.selectType = ''
      if (chartType === 'ratioChart') {
        await this.getProfitData()
      } else if (chartType === 'rankingChart') {
        await this.fetchTeamRankingOptionChartData(params) // 团队排行
      } else {
        await this.getCurrentChartData(params)
        await this.getProfitData()
        await this.fetchTeamRankingOptionChartData(params)
      }
    },
    // 收支结构分析 总利润
    async getProfitData() {
      const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)
      const profitData = await this.getData(getProfitData, params)
      this.incomePayData = {
        ...this.incomePayData,
        totalProfit: profitData
      }
      this.isLoading = false
    },
    // 收支结构分析 团队排行参数处理
    async fetchTeamRankingOptionChartData(params, chartType) {
      if (chartType === 'teamIncome' || chartType === 'staffIncome') {
        // 部门收入
        await this.getRankingData(params, chartType, getIncomeRanking)
      } else if (chartType === 'teamProfit' || chartType === 'staffProfit') {
        // 部门利润
        await this.getRankingData(params, chartType, getProfitRanking)
      } else {
        await this.getRankingData(params, 'teamIncome', getIncomeRanking)
        await this.getRankingData(params, 'teamProfit', getProfitRanking) 
      }
    },
    async getRankingData(params, chartType, getDataFunction) {
      const data = await this.getData(getDataFunction, params)
      // 处理企微人员
      if (this.isOpenData) {
        if (window.WWOpenData?.initCanvas) {
          window.WWOpenData.initCanvas()
          window.WWOpenData.enableCanvasSharing()
        }

        let allHandleStaffDataPromise = this.handleStaffData(data.list)
        await Promise.all([allHandleStaffDataPromise])
      }

      this.rankingMap[chartType].data = this.rankingMap[chartType].data.concat(data.list || [])
      this.rankingMap[chartType].hasNextPage = data.hasNextPage
      this.isLoading = false
    },
    // 处理企微人员
    async handleStaffData(list) {
      if (!list) return []

      for (let index = 0; index < list.length; index ++) {

        if(!list[index].staffId) continue;

        let items = [{
          type: 'userName',
          id: list[index].staffId
        }]

        const result = await new Promise((resolve, reject) => {
          window.WWOpenData.prefetch({ items }, (err, data) => {
            if (err) {
              return reject(err)
            }
            resolve(data)
          })
        })

        try {
          list[index] = Object.assign(list[index], { name: result.items[0]?.data })
        } catch (error) {
          console.warn(error)
        }

      }
      return list
    },
    // 库存周转率参数处理
    fetchStockTurnoverOptionChartData(value) {
      const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)
      this.getCurrentChartData(params)
    },
    // 工单满意度参数处理
    fetchTaskOptionChartData(value) {
      this.$nextTick(async() => {
        // 对比分析维度参数
        this.chartOption[this.reportKey] = { selectType: '' }
        if(value) {
          this.chartOption[this.reportKey] = value
        }
        this.currentChartOptions = this.chartOption[this.reportKey]
        const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)
        this.getCurrentChartData(params)
        // 工单客户满意度
        if (this.chart === 'task-customer-satisfaction') {
          // this.getPieData(params)
          this.pieChartData = {}
          const data = await this.getData(getSatisfactionPine, params)
          this.pieChartData = data
        }
      })
    },
    fetchTimeOptionChartData(value) {
      this.chartOption[this.reportKey] = {};

      this.$nextTick(() => {
        if (value) {
          this.chartOption[this.reportKey] = value;
        } else {
          // 初始化选项
          this.chartOption[this.reportKey] = this.$refs[this.optionType].timeOption;
        }
        
        /* 
          selectType传参按照后端要求：
            1.从”开始工单“开始计算 2.从”接受工单“开始计算 3.从”指派工单“开始计算 4.从”创建工单“开始计算 5.从”工单关联事件创建“开始计算
            6.从“客户提报事件/工单创建“至“工单接受” 8.从”客户提报事件/工单创建“至“工单开始” 7.从“客户提报事件/工单创建“至“工单指派”
            9.按照”附加组件工时记录的工作用时“计算 10.按照”开始工单至完成工单“计算
        */
        const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams);
        
        if (this.pageInfo.value === 'average-response-time') {
          params.selectType = Number(params.selectType) + 5;
        } else if (this.pageInfo.value === 'average-maintenance-time') {
          params.selectType = Number(params.selectType) + 8;
        } 
        
        this.currentChartOptions = this.chartOption[this.reportKey]
        
        this.getCurrentChartData(params);
      })
    },
    fetchPeriodOptionChartData(value) {
      this.chartOption[this.reportKey] = {};
      // this.getCurrentChartData(this.fetchParams);
      this.$nextTick(async() => {
        if (value) {
          this.chartOption[this.reportKey] = value;
        } else {
          if (this.optionType === 'chart-period-setting') {
            // 及时关单率
            // this.chartOption[this.reportKey] = this.$refs[this.optionType].initList;
            const initList = [
              {
                startIndex: 0,
                endIndex: 1,
              },
              {
                startIndex: 1,
                endIndex: 2,
              },
              {
                startIndex: 2,
                endIndex: 3,
              },
              {
                startIndex: 3,
                endIndex: 4,
              }
            ]
            const closeForm = {
              // 周期统计维度(0:分钟 1:小时 2:天)
              closeDimension: 2,
              aroundSearchQueryList: initList,
            }
            this.chartOption[this.reportKey] = closeForm
          } else if (this.optionType === 'chart-inspection-time-setting') {
            // todo 需要和后端对接重命名
            this.chartOption[this.reportKey] = { periodArr: this.$refs[this.optionType].periodArr }
          }
        }
        this.currentChartOptions = this.chartOption[this.reportKey]
        const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams);
        // this.getCloseAroundData(params);
        this.getCurrentChartData(params)
        this.lineChartData = []
        const data = await this.getData(getCloseAroundData, params)
        this.lineChartData = data?.closeAroundList
      })
    },
    // 获取下钻图表等数据
    fetchTableData(value, chartType, tabType) {
      if (value !== 'page') {
        this.tablePageParams = {
          page: 1,
          pageSize: 10,
          totalSize: 0
        }
      }
      // 收支结构分析
      if (this.chart === 'spare-part-sale' && chartType === 'incomeProfit') {
        return this.fetchIncomeProfitOptionTableParams(value, chartType);
      }

      if (chartType !== 'teamIncome' && chartType !== 'teamProfit') {
        this.foldTable(true, chartType)
      }

      let params = Object.assign({}, this.tablePageParams, this.chartOption[this.reportKey], this.fetchParams)

      if (this.optionType === 'chart-time-option-setting') {
        // 平均用时
        if (this.pageInfo.value === 'average-response-time') {
          params.selectType = Number(params.selectType) + 5;
        } else if (this.pageInfo.value === 'average-maintenance-time') {
          params.selectType = Number(params.selectType) + 8;
        }
        this.getCurrentTableData(params);
      } else if (this.optionType === 'chart-period-setting') {
        // 及时关单率
        let queryList = []
        if (value && tabType === 'closeTab') {
          queryList = [ value ]
        } else if (value === 'page') {
          queryList = this.aroundSearchQueryList
        } else {
          this.tablePeriodSelectTabs = '0'
          queryList = [ JSON.parse(JSON.stringify(params.aroundSearchQueryList))[0] ] // 默认传第一项
        }
        this.aroundSearchQueryList = queryList
        params.aroundSearchQueryList = this.aroundSearchQueryList
        this.getCurrentTableData(params)
      } else if (this.optionType === 'chart-comment') {
        // 服务人效
        this.getCurrentTableData(params)
      } else if (this.optionType === 'chart-repeat-maintenance-setting') {
        // 重复维修率
        this.fetchRepeatMaintenanceOptionTableParams(value, chartType, tabType)
      } else if (this.optionType === 'chart-task-option-setting') {
        // 工单回访率
        let id = ''
        if(value !== 'page') {
          this.positionTime = value?.name || ''
        }
        if (this.chartOption[this.reportKey]?.selectType) {
          // 如果选了维度 把id传给后端
          // this.chartOption[this.reportKey] = Object.assign(this.chartOption[this.reportKey], value)
          id = value?.seriesId ?? this.chartOption[this.reportKey].id
        }
        this.chartOption[this.reportKey] = Object.assign(this.chartOption[this.reportKey], { id, positionTime: this.positionTime })
        params = Object.assign({}, this.tablePageParams, this.chartOption[this.reportKey], this.fetchParams)
        this.getCurrentTableData(params)
      } else {
        // 收支结构分析
        if (this.chart === 'revenue-expenditure-analysis') {
          return this.fetchIncomePayOptionTableParams(value, chartType)
        }
        // 工单客户满意度
        this.fetchTaskSatisfactionOptionTableParams(value, chartType, tabType)
      }
    },
    // 备件营收分析 收入和利润切换tab
    fetchIncomeProfitOptionTableParams(value, chartType){
      this.salesMap['serviceIncomeProfitData']['page'] = 1;
      this.salesMap['serviceIncomeProfitData']['data'] = [];

      this.salesMap['spareIncomeProfitData']['page'] = 1;
      this.salesMap['spareIncomeProfitData']['data'] = [];

      this.chartOption[this.reportKey] = {
        ...this.chartOption[this.reportKey],
        ...value
      }

      this.currentChartOptions = this.chartOption[this.reportKey];
      const params = Object.assign({}, this.fetchParams, this.chartOption[this.reportKey]);
      params.tags = params.tags.map(x=>x.id);

      this.featchMeetRateOptionChartData(params, chartType);
    },
    // 重复维修率
    fetchRepeatMaintenanceOptionTableParams(value, chartType, tabType) {
      this.chartOption[this.reportKey] = {
        ...{ selectType: 'MAN'},
        ...this.chartOption[this.reportKey]
      }
      if (value && tabType === 'tab') {
        this.chartOption[this.reportKey] = value
      }
      this.currentChartOptions = this.chartOption[this.reportKey]
      const params = Object.assign({}, this.tablePageParams, this.chartOption[this.reportKey], this.fetchParams)
      params.repeatedSearchQueries =  [ params.repeatedSearchQueries[0] ] // 默认传第一项
      if (value === 'page') {
        params.repeatedSearchQueries = this.repeatedSearchQueries
      }
      if (value && tabType === 'closeTab') params.repeatedSearchQueries = [ value ]
      this.repeatedSearchQueries = params.repeatedSearchQueries
      this.getCurrentTableData(params)
    },
    // 收支结构分析下钻table参数处理
    async fetchIncomePayOptionTableParams(value, chartType) {
      // 下钻前清空原有数据
      let childType = ''
      if (chartType === 'teamIncome') {
        childType = 'staffIncome'
        this.rankingMap[childType]['data'] = []
        this.rankingMap[childType]['page'] = 1
        this.rankingMap[childType]['tagId'] = value?.tagId
      }
      if (chartType === 'teamProfit') {
        childType = 'staffProfit'
        this.rankingMap[childType]['data'] = []
        this.rankingMap[childType]['page'] = 1
        this.rankingMap[childType]['tagId'] = value?.tagId
      }

      this.chartOption[this.reportKey] = {
        ...value,
        ...this.rankingMap[childType]
      }
      this.currentChartOptions = this.chartOption[this.reportKey]
      let params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)
      // 部门收入人员下钻
      if (chartType === 'teamIncome') {
        this.getRankingData(params, 'staffIncome', getIncomeRanking)
      }
      // 部门利润人员下钻
      if (chartType === 'teamProfit') {
        this.getRankingData(params, 'staffProfit', getProfitRanking)
      }
    },
    // 获取工单满意度下钻table参数
    fetchTaskSatisfactionOptionTableParams(value, chartType, tabType) {
      this.$nextTick(() => {
        let ousideSelectType = '' // 默认选中人员TAB
        if ((!tabType && (chartType === 'Line' || chartType === 'Pie')) && value !== 'page') {
          ousideSelectType = 'MAN'
        } else {
          ousideSelectType = this.chartOption[this.reportKey]?.ousideSelectType
        }
        if (tabType) {
          ousideSelectType = value?.ousideSelectType
        }

        let idMap = {}
        idMap['id'] = ''
        if (this.chartOption[this.reportKey]?.selectType) {
          idMap['id'] = value?.seriesId || this.chartOption[this.reportKey]?.id
        }
        
        if ((tabType || (chartType === 'Line' || chartType === 'Pie')) && value !== 'page') {
          this.tablePageParams = {
            page: 1,
            pageSize: 10,
            totalSize: 0
          }
        }

        this.chartOption[this.reportKey] = {
          ...this.chartOption[this.reportKey],
          ...idMap,
          ousideSelectType
        }

        this.currentChartOptions = this.chartOption[this.reportKey]

        let params = Object.assign({}, this.tablePageParams, this.chartOption[this.reportKey], this.fetchParams)
        // 满意度饼图下钻
        let requestUrl = ''
        if (chartType === 'Line') {
          // 满意度折线下钻
          requestUrl = '/api/dataware/outside/satisfaction/getSatisfactionBrokenTypeData'
          this.showLineTable = true
        } else {
          requestUrl = '/api/dataware/outside/satisfaction/getSatisfactionPineData'
          this.showPieTable = true
        }
        this.getCurrentTableData(params, requestUrl)
      })
    },
    // 获取当前下钻列表的数据
    async getCurrentTableData(params, requestUrl) {
      try {
        this.tableData = []
        let chartTableAPI = this.pageInfo.tableUrl || requestUrl
        if (!chartTableAPI) return
        const { code, msg, data } = await http.post(chartTableAPI, params)

        if (code !== 200) {
          return this.$message({
            message: msg,
            duration: 1500,
            type: 'error',
          });
        }
        
        this.buildTableData(data)

      } catch (error) {
        console.log(error);
      }
    },
    buildTableData(data) {
      try {
        let { 
          // 用时数据 
          men, 
          // 单位
          timeUnit, 
          // 关单周期数据 重复维修率
          dataDeliveryUserFormDTOPageResult, 
          // 服务人效
          pageList,
          // 工单回访
          dataReviewDTOS, 
          // 满意度饼图
          dataSatisfactionPineAnyDTOList,
          // 满意度折线
          dataSatisfactionBrokenDTOList
        } = data || {}

        let { 
          list = [], 
          page, 
          size, 
          totalSize 
        } = men || dataDeliveryUserFormDTOPageResult || pageList || dataReviewDTOS || {}

        let { 
          list: pieTableData,
          page: piePage, 
          size: pieSize, 
          totalSize: pieTotalSize
        } = dataSatisfactionPineAnyDTOList || {}

        let {
          list: lineTableData,
          page: linePage, 
          size: lineSize, 
          totalSize: lineTotalSize
        } = dataSatisfactionBrokenDTOList || {}
        // 用时单位
        this.timeUnit = timeUnit

        this.tableData = list || []
        this.pieTableData = pieTableData || []
        this.lineTableData = lineTableData || []

        this.tablePageParams = { // 临时解决 方便测试
          page: page || piePage || linePage,
          pageSize: size || pieSize || lineSize,
          totalSize: totalSize || pieTotalSize || lineTotalSize
        }
      } catch(error) {
        console.log(error)
      }
    },
    foldTable(val, chartType) {
      this.isTableShow = val
      if(!val){
        this.showLineTable = false
        this.showPieTable = false
        this.showTaskTable = false
      } else {
        if (chartType === 'Line') {
          this.showLineTable = val
          this.showPieTable = false
        } else if (chartType === 'Pie'){
          this.showPieTable = val
          this.showLineTable = false
        }
      }
    },
    foldTaskTable(value, taskIds) {
      this.chartOption[this.reportKey]['ids'] = taskIds
      this.currentChartOptions = this.chartOption[this.reportKey]

      this.showTaskTable = value
    },
    handleSizeChange(value, chartType) {
      this.tablePageParams.pageSize = value;
      this.tablePageParams.page = 1
      this.fetchTableData('page', chartType)
    },
    handleNumChange(value, chartType) {
      this.tablePageParams.page = value;
      this.fetchTableData('page', chartType)
    },
    categoryMore(value) {
      // 备件营收分析 收入和利润加载更多
      if(value === 'spareIncomeProfitData' || value === 'serviceIncomeProfitData'){
        this.salesMap[value]['page']++;

        this.currentChartOptions = this.chartOption[this.reportKey]
        const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)

        this.featchMeetRateOptionChartData(params, value);
        return;
      }

      this.categoryType = value
      this.chartOption[this.reportKey]['page'] = (++ this.rankingMap[this.categoryType].page)
      if (value === 'teamIncome' || value == 'teamProfit') {
        this.chartOption[this.reportKey]['tagId'] = ''
      }
      if (value === 'staffIncome') {
        this.chartOption[this.reportKey]['tagId'] = this.rankingMap['staffIncome'].tagId
      }
      if (value === 'staffProfit') {
        this.chartOption[this.reportKey]['tagId'] = this.rankingMap['staffProfit'].tagId
      }
      this.currentChartOptions = this.chartOption[this.reportKey]
      const params = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)
      this.fetchTeamRankingOptionChartData(params, value)
    },
    switchSampleData(value) {
      this.isExample = value?.isExample
      this.chartOption[this.reportKey] = value
      this.currentChartOptions = this.chartOption[this.reportKey]
      
      const chartParams = Object.assign({}, this.chartOption[this.reportKey], this.fetchParams)
      
      if (!this.isExample) {
        if (this.pageInfo.value === 'average-response-time') {
          chartParams.selectType = Number(chartParams.selectType) + 5;
        } else if (this.pageInfo.value === 'average-maintenance-time') {
          chartParams.selectType = Number(chartParams.selectType) + 8;
        } 
      }
      
      if (this.chart === 'timely-closing-rate') {
        // 及时关单率
        this.fetchPeriodOptionChartData(chartParams)
      } else if (this.chart === 'repeated-maintenance-rate') {
        // 重复维修率
        this.fetchRepeatMaintenanceOptionChartData(chartParams)
      } else if (this.chart === 'task-customer-satisfaction') {
        // 工单客户满意度
        this.fetchTaskOptionChartData(chartParams)
      } else if (this.chart === 'revenue-expenditure-analysis') {
        // 收支结构分析
        this.fetchIncomePayOptionChartData(chartParams)
      } else if (this.chart === 'spare-part-sale') {
        // 备件营收分析
        this.fetchChartMeetReatOptionChartData(chartParams)
      } else {
        this.getCurrentChartData(chartParams)
      }

      // if (!this.isExample) {
        this.isTableShow = false
        this.showPieTable = false
        this.showLineTable = false
        this.showTaskTable = false
      // }
    },
    /**
     * @description 导出事件
     */
    exportTableData(type, pageParams) {
      const exroprtAPI = this.buildExportAPI(type)
      // 导出全部 后端要求分页参数全部传0 导出部分 传当前页码
      const tablePageParams = {
        page: pageParams?.page || 0,
        pageSize: pageParams?.pageSize || 0
      }
      let params = Object.assign({}, tablePageParams, this.chartOption[this.reportKey], this.fetchParams)
      const timeExportMap = {
        'average-maintenance-time': 1,
        'average-response-time': 2,
        'average-service-time': 3
      }
      if (timeExportMap[this.chart]) {
        params.searchType = timeExportMap[this.chart]
      }

      if (this.pageInfo.value === 'average-response-time') {
        params.selectType = Number(params.selectType) + 5;
      } else if (this.pageInfo.value === 'average-maintenance-time') {
        params.selectType = Number(params.selectType) + 8;
      }
      
      if (this.pageInfo.value === 'timely-closing-rate') {
        // params.aroundSearchQueryList = this.aroundSearchQueryList
        params.aroundSearchQueryList = this.currentChartOptions?.aroundSearchQueryList || [];
      }

      exroprtAPI(params).then(res => {
        if(res.code !== 200) {
          return this.$message({
            message: res.msg,
            duration: 1500,
            type: 'error',
          })
        }
        window.parent.showExportList()
        window.parent.exportPopoverToggle(true)
      }).catch(error => {
        console.log(error)
      })
    },
    buildExportAPI (type) {
      let API

      if (this.chart === 'average-response-time') API = exportResponsePartData
      if (this.chart === 'average-service-time') API = exportServicePartData
      if (this.chart === 'average-maintenance-time') API = exportMaintenancePartData
      if (this.chart === 'timely-closing-rate') API = exportClosingPartData
      if (this.chart === 'service-human-efficiency') API = exportHumanPartData
      if (this.chart === 'repeated-maintenance-rate') API = exportRepeatedPartData
      if (this.chart === 'repeated-maintenance-rate' && type === 'task') API = exportRepeatedTaskPartData
      if (this.chart === 'task-return-visit') API = exportTaskReturnPartData
      if (this.chart === 'task-customer-satisfaction' && type === 'pie') API = exportTaskSatisfactionPiePartData
      if (this.chart === 'task-customer-satisfaction' && type === 'task') API = exportTaskSatisfactionPieTaskPartData
      if (this.chart === 'task-customer-satisfaction' && type === 'line') API = exportTaskSatisfactionBrokenLinePartData

      return API;
    },
    changePeriodTableSelectTabs(value) {
      this.tablePeriodSelectTabs = value
    },
    getCellData(row, column) {
      const keys = column.property
      const taskIds = row[`${keys}_taskId`]
      this.showTaskTable = true

      this.chartOption[this.reportKey]['ids'] = taskIds
      this.currentChartOptions = this.chartOption[this.reportKey]

      this.$nextTick(() => {
        if(!taskIds) return;
        try{
          this.$refs['chartTaskTable'].getData(taskIds, getRepeatBrokenTaskData)
        }catch(err){
          console.log('getCellData~~~~~~`',err)
        }
      })
    },
    // 下钻连接查看权限
    async getUserModuleAuth(){
      try{
        const { code, data } = await getUserModuleAuth();
        if(code !== 200) return;
        this.userModuleAuth = data;
      }catch(err){
        console.log('getUserModuleAuth~~~~~~`',err)
      }
    }
  },
  async mounted() {
    this.reportKey = this.queryObject?.chartName
    this.parentKey = this.queryObject?.menuName

    await this.getMenuData();

    this.getCurrentPageData();
    this.getUserModuleAuth();
  },
  components: {
    [ChartsMenu.name]: ChartsMenu,
    [ChartsHeader.name]: ChartsHeader,
    [ComponentNameEnum.ChartsSearch]: ChartsSearch,
    BarChart,
    StackedLineChart,
    BarLineChart,
    BarRevenueChart,
    PieChart,
    PieStackedLineChart,
    IncomePayChart,
    DrillDownTable,
    ChartTimeOptionSetting,
    ChartComment,
    ChartPeriodSetting,
    ChartInspectionTimeSetting,
    ChartTaskOptionSetting,
    ChartStockTurnoverOptionSetting,
    ChartSatisfiedPeriodSetting,
    ChartRepeatMaintenanceSetting,
    ChartTaskTable
  },
};
</script>

<style lang="scss" scoped>
.charts-index {
  display: flex;
  justify-content: space-between;
  min-height: calc(100% - 1px);
  .charts-left {
    min-width: 210px;
    .charts-left-fixed {
      width: 210px;
      z-index: 2000;
      position: fixed;
      overflow: hidden;
      background-color: #fff;
    }
    .charts-index-back {
      height: 42px;
      line-height: 42px;
      padding-left: 22px;
      color: #595959;
      span, i {
        font-size: 12px;
        cursor: pointer;
      }
      .charts-index-back-title {
        margin-left: 10px;
        font-size: 16px;
        font-weight: bold;
      }
    }
    .charts-index-search {
      margin: 0 8px 10px 8px;
    }
  }
  .charts-right {
    flex: 1 1 auto;
    padding: 12px;
    padding-bottom: 0;
    overflow: hidden;
    >div:last-child {
      height: 100%;
    }
  }
  .charts-content {
    width: 100%;
    // min-height: 450px;
    height: 100%;
    // padding: 16px;
    // background-color: #fff;
    // border-radius: 4px;
    // overflow: auto;
    .chart-card-header {
      padding: 16px;
      border-radius: 4px 4px 0 0;
      background-color: #fff;
    }
    .chart-card-radius {
      border-radius: 0 0 4px 4px;
    }
    .charts-content-two {
      margin-bottom: 12px;
    }
    .card-radius {
      border-radius: 4px;
      margin-bottom: 12px;
    }
  }
}
</style>
<style lang="scss">
.chart-tooltip {
  margin-left: 4px;
  font-size: 14px;
  color: #595959;
}

.el-tooltip__popper {
  min-width: 300px;
}

.el-dialog.close-dialog {
  .el-form-item__content {
    .el-form-item-line {
      .el-form-item-line-index {
        width: 20px;
      }
    }
  }
}

.charts-search-block .charts-search .el-select {
  width: 230px;
}

@media screen and (max-width: 1200px) {
  .charts-search-block .charts-search .el-select {
    width: 212px;
  }
  .charts-search-block .charts-search .charts-search-child .task-span {
    width: 234px;
  }
  .charts-search-block .charts-search .publink-date-period .el-select {
    width: 60px;
  }
  .charts-search-block .charts-search .publink-date-period .el-date-editor {
    width: 233px !important;
  }
  .charts-index .charts-right {
    min-width: 978px !important;
    max-width: 1200px !important;
    width: 978px !important;
  }
  .charts-index .charts-left {
    min-width: 210px !important;
  }
  .charts-search-block .charts-search-block-content {
    min-width: 740px !important;
  }
  .charts-search-block-operator button:nth-of-type(1) {
    margin-left: 0 !important;
  }
}

@media screen and (max-width: 1020px) {
  .charts-search-block .charts-search .el-select {
    width: 502px;
  }
  .charts-search-block .charts-search .charts-search-child .task-span {
    width: 502px;
  }
  .charts-search-block .charts-search .publink-date-period .el-select {
    width: 80px;
  }
  .charts-search-block .charts-search .publink-date-period .el-date-editor {
    width: 190px !important;
  }
  .charts-index .charts-right {
    min-width: 798px !important;
    max-width: 1020px !important;
    width: 798px !important;
  }
  .charts-index .charts-left {
    min-width: 210px !important;
  }
  .charts-search-block .charts-search-block-content {
    min-width: 560px !important;
  }
  .charts-search-block-operator button:nth-of-type(1) {
    margin-left: 0 !important;
  }
  .charts-search-block .charts-search .charts-search-child {
    flex-flow: column !important;
  }
  .income-pay-warp {
    flex-flow: column !important;
  }
}

@media screen and (max-width: 880px) {
  .charts-search-block .charts-search .el-select {
    width: 378px;
  }
  .charts-search-block .charts-search .charts-search-child .task-span {
    width: 378px;
  }
  .charts-search-block .charts-search .publink-date-period .el-select {
    width: 60px;
  }
  .charts-search-block .charts-search .publink-date-period .el-date-editor {
    width: 138px !important;
  }
  .charts-index .charts-right {
    min-width: 658px !important;
    max-width: 880px !important;
    width: 658px !important;
  }
  .charts-index .charts-left {
    min-width: 210px !important;
  }
  .charts-search-block .charts-search-block-content {
    min-width: 480px !important;
  }
  .charts-search-block-operator button:nth-of-type(1) {
    margin-left: 0 !important;
  }
  .charts-search-block .charts-search .charts-search-child {
    flex-flow: column !important;
  }
  .income-pay-warp {
    flex-flow: column !important;
  }
}
</style>
